<script setup lang="ts">
import {IconRefresh} from "@arco-design/web-vue/es/icon";
import {getCurrentInstance, reactive, ref} from "vue";
import type {BaseRsp, ListData, PageParamsType} from "@/api";
import {Message, type TableColumnData, type TableData, type TableRowSelection} from "@arco-design/web-vue";
import {dateTimeFormat} from "@/utils/date";

interface Props {
  url: (params: PageParamsType) => Promise<BaseRsp<ListData<any>>>
  columns: TableColumnData[]
  limit?: number
  optionTypeList?: optionType[]
  check?: boolean
  filterOptionList?: optionType[]
  add?: string
  update?: string
  del?: string
  visibleAdd?: boolean
  visibleUpdate?: boolean
}

// 拿到父组件传过来的值
const props = defineProps<Props>()

// 给初始值
const {limit = 10,} = props

export interface optionType {
  label: string
  value: string | number | undefined
  column?: string
  options?: optionType[]
}

const actionValue = ref<string | number | undefined>(undefined)
const loading = ref<boolean>(true)


const mitt = getCurrentInstance()

const data = reactive<ListData<any>>({
  list: [],
  count: 0,
})

const params = reactive<PageParamsType>({
  page: 1,
  limit: limit,
  key: "",
})

async function getList() {
  loading.value = true
  let rsp = await props.url(params)
  data.count = rsp.data.count
  data.list = rsp.data.list
  loading.value = false
}

function pageChange() {
  getList()
}

function search() {
  params.page = 1
  getList()
}

function refresh() {
  params.page = 1
  params.key = ""
  getList()
}

// 暴露给父自组件
// defineExpose({refresh})

const selectedKeys = ref<number[] | string[]>([]);
const rowSelection = reactive<TableRowSelection>({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});

// 传id到父组件去删除
function del(record: TableData) {
  mitt?.proxy?.$Bus.emit('del', [record['id']])
}

function actionMethod() {
  if (actionValue.value === 1) {
    if (selectedKeys.value.length === 0) {
      Message.warning("请选择删除的数据")
      return
    }
    // 批量删除
    mitt?.proxy?.$Bus.emit('del', selectedKeys.value)
  }
}

function filterChange(item: any, value: any) {
  console.log(item, value)
}


function addModal() {
  mitt?.proxy?.$Bus.emit("openAddModal")
}

function updateModal(record: TableData) {
  console.log(record)
  mitt?.proxy?.$Bus.emit("openUpdateModal", record)
}

mitt?.proxy?.$Bus.on('refresh', () => {
  refresh()
})

// 调用查询接口
getList()
</script>

<template>
  <div class="blog_table">
    <div class="blog_table_head">
      <div class="action_create" v-if="props.add" @click="addModal">
        <a-button type="primary">{{ props.add }}</a-button>
      </div>
      <div class="action_group" v-if="props.optionTypeList !=  undefined && props.optionTypeList.length">

        <a-select placeholder="操作" style="width: 200px" allow-clear :options="props.optionTypeList"
                  v-model="actionValue">

        </a-select>
        <a-popconfirm content="确认执行?" @ok="actionMethod">
          <a-button type="primary" status="danger" v-if="actionValue">执行</a-button>
        </a-popconfirm>

      </div>
      <div class="action_search">
        <a-input-search placeholder="搜索" v-model="params.key" @search="search" @keyup.enter="search">
        </a-input-search>
      </div>
      <slot class="action_search_other">

      </slot>
      <div class="action_filter" v-if="props.filterOptionList !=  undefined && props.filterOptionList.length">
        <a-select v-for="item in  props.filterOptionList" :placeholder="item.label" :options="item.options"
                  @change="filterChange(item, $event)">

        </a-select>
      </div>
      <div class="action_slot"></div>
      <div class="action_flush">
        <a-button @click="refresh">
          <IconRefresh></IconRefresh>
        </a-button>
      </div>
    </div>
    <a-spin class="blog_table_data" :loading="loading" tip="加载中">
      <div class="blog_table_source">
        <a-table row-key="id" :columns="props.columns" :data="data.list" :row-selection="check? rowSelection:undefined"
                 v-model:selectedKeys="selectedKeys" :pagination="false">
          <template #columns>
            <template v-for="item in props.columns">

              <a-table-column v-if="item.render" :title="item.title as string">
                <template #cell="data">
                  <component :is="item.render(data)"></component>
                </template>
              </a-table-column>

              <a-table-column v-else-if="!item.slotName" :title="item.title as string" :data-index="item.dataIndex">

              </a-table-column>

              <a-table-column v-else :title="item.title as string">

                <template #cell="{record}" v-if="item.slotName === 'action'">
                  <div class="blog_cell_actions">

                    <a-button type="primary" v-if="props.update" @click="updateModal(record)">
                      {{ props.update }}
                    </a-button>

                    <a-popconfirm content="是否确认删除?" v-if="props.del" @ok="del(record)">
                      <a-button status="danger" type="primary">{{ props.del }}</a-button>
                    </a-popconfirm>

                  </div>
                </template>

                <template #cell="{record}" v-else-if="item.slotName === 'created_at'">
                  <span>{{ dateTimeFormat(record.created_at) }}</span>
                </template>

                <template #cell="{record}" v-else-if="item.slotName === 'updated_at'">
                  <span>{{ dateTimeFormat(record.created_at) }}</span>
                </template>

                <template #cell="{record}" v-else-if="item.slotName === 'avatar'">
                  <a-avatar :image-url="record.avatar"></a-avatar>
                </template>

                <template v-else #cell="{record}">
                  <slot :name="item.slotName" :record="record"></slot>
                </template>

              </a-table-column>
            </template>

          </template>
        </a-table>

      </div>
      <div class="blog_table_page">
        <a-pagination :total="data.count" v-model:current="params.page" :default-page-size="params.limit"
                      @change="pageChange"
                      show-total
                      show-jumper/>
      </div>
    </a-spin>

  </div>
</template>

<style lang="scss">
.blog_table {
  background-color: var(--color-bg-1);
  border-radius: 5px;

  .blog_table_head {
    padding: 20px 20px 10px 20px;
    border-bottom: 1px solid var(--bg);
    display: flex;
    align-items: center;
    position: relative;

    > div {
      margin-right: 10px;
    }

    .action_group {
      display: flex;

      button {
        margin-left: 10px;
      }
    }

    .action_filter {
      display: flex;

      > .arco-select {
        margin-right: 10px;
      }
    }

    .action_flush {
      position: absolute;
      right: 20px;
      margin-right: 0;

      button {
        margin: 0 10px;
      }
    }

  }

  .blog_table_data {
    width: 100%;
    padding: 10px 20px 20px 20px;

    .blog_table_source {
      .blog_cell_actions {
        > button {
          margin-right: 10px;

          &:last-child {
            margin-right: 0;
          }
        }
      }
    }

    .blog_table_page {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }

}
</style>
